package com.letv.android.client.episode.parser;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.letv.core.bean.AlbumNew;
import com.letv.core.bean.AlbumNewListByDateBean;
import com.letv.core.bean.TabAllDataBean;
import com.letv.core.bean.TabOuterVideoInfoBean;
import com.letv.core.bean.TabTextLinkBean;
import com.letv.core.bean.TabVideoListBean;
import com.letv.core.bean.VideoBean;
import com.letv.core.bean.VideoListBean;
import com.letv.core.parser.LetvMasterParser;
import com.letv.core.utils.LogInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;

/*
 * Tab 合并接口数据解析
 */
public class TabCombineEpisodeParser extends LetvMasterParser<TabAllDataBean> {
	private static final String BODY = "body";
	private static final String TABVIDEOLIST = "tabVideoList";
	private static final String TABRELATE = "tabRelate";
	
	private static final String VIDEOINFO = "videoInfo";
	private static final String ALBUMINFO = "albumInfo";
	private static final String OUTERVIDEOINFO = "OuterVideoInfo";
	
	private static final String ISCURRENT = "isCurrent";
	private static final String DATA = "data";
	
	private static final String VIDEOLIST = "videoList";
	private static final String STYLE = "style";
	private static final String TEXTLINK = "textLink";
		
	
	private static final String STYLE_GRIDVIEW = "1";
	private static final String STYLE_LISTVIEW = "2";
	private static final String STYLE_EXPLISTVIEW = "3";
	
	private TabAllDataBean mTabAllDataBean;
	
	@Override
	protected TabAllDataBean parse(JSONObject data) {
		if (data == null) {
			return null;
		}

		JSONObject object = getJSONObject(data, BODY);
		if (JSONObject.NULL.equals(object) || object.length() == 0) {
			return null;
		}
		mTabAllDataBean = new TabAllDataBean();
		JSONObject tabVideoList = getJSONObject(object, TABVIDEOLIST);
		JSONObject tabRelate = getJSONObject(object, TABRELATE);
		if (tabVideoList != null && getString(tabVideoList, ISCURRENT).equals("1")) {
			mTabAllDataBean.setNormalVideo(true);
			parseTabEpisode(getJSONObject(tabVideoList, DATA));
		}
		else if (tabRelate != null && getString(tabRelate, ISCURRENT).equals("1")) {
			mTabAllDataBean.setNormalVideo(false);
			parseTabRelate(getJSONObject(tabRelate, DATA));
		}
		
		
		String videoInfo = getString(object, VIDEOINFO);
		if (!TextUtils.isEmpty(videoInfo)) {
			mTabAllDataBean.setVideoInfo(JSON.parseObject(videoInfo, VideoBean.class));
		}
		String albumInfo = getString(object, ALBUMINFO);
		if (!TextUtils.isEmpty(albumInfo)) {
			mTabAllDataBean.setAlbumInfo(JSON.parseObject(albumInfo, AlbumNew.class));
		}
		String outerVideoInfo = getString(object, OUTERVIDEOINFO);
		if (!TextUtils.isEmpty(outerVideoInfo)) {
			mTabAllDataBean.setOuterVideoInfo(JSON.parseObject(outerVideoInfo, TabOuterVideoInfoBean.class));
		}
		return mTabAllDataBean;
	}
	
	private void parseTabEpisode(JSONObject tabData) {		
		String textLink = getString(tabData, TEXTLINK);
		String style = getString(tabData, STYLE); 
		String videoList = getString(tabData, VIDEOLIST);
		
		mTabAllDataBean.getTabVideoList().getTabIndicatorData().setStyle(style);
		
		if (!TextUtils.isEmpty(textLink)){
			TabTextLinkBean tabTextLinkBean = JSON.parseObject(textLink, TabTextLinkBean.class);
			mTabAllDataBean.getTabVideoList().getTabIndicatorData().setTextLink(tabTextLinkBean);
		}
		
		if (style.equals(STYLE_GRIDVIEW)) {
			parseVideoGrid(videoList);
		}
		else if (style.equals(STYLE_LISTVIEW)) {
			parseVideoList(videoList);
		}
		else if (style.equals(STYLE_EXPLISTVIEW)) {
			parseVideoExpListByDate(videoList);
		}
	}	
	
	private void parseTabRelate(JSONObject tabData) {
		String style = getString(tabData, STYLE); 
		String videoList = getString(tabData, VIDEOLIST);
		
		mTabAllDataBean.getTabVideoList().getTabIndicatorData().setStyle(style);
		if (style.equals(STYLE_LISTVIEW)) {
			parseRelateList(videoList);
		}		
	}
			
	/*
	 * Video List
	 */
	private void parseVideoGrid(String data) {
		mTabAllDataBean.getTabVideoList().getTabIndicatorData().setVideoList(JSON.parseObject(data, TabVideoListBean.class));
	}
	
	private void parseVideoList(String data) {
		mTabAllDataBean.getTabVideoList().getTabIndicatorData().setVideoList(JSON.parseObject(data, TabVideoListBean.class));
	}	
	
	private void parseVideoExpListByDate(String data) {
//		mTabAllDataBean.getTabVideoList().getTabIndicatorData().setVideoList(JSON.parseObject(data, TabVideoListBean.class));
		try {
			mTabAllDataBean.getTabVideoList().getTabIndicatorData().getVideoList().setAlbumNewListByDatePlayerLibs(parse2AlbumNewListByDatePlayerLibs(new JSONObject(data)));
		} catch (JSONException e) {
			e.printStackTrace();
			LogInfo.log("hong", "parseVideoExpListByDate exception!");
		}
	}
	
	private AlbumNewListByDateBean parse2AlbumNewListByDatePlayerLibs(JSONObject data) {
		try {
            AlbumNewListByDateBean albumNewListByDatePlayerLibs = new AlbumNewListByDateBean();
            Iterator<String> iters = data.keys();
            ArrayList<String> newList = setNewDate(new ArrayList<String>() , iters);
            LinkedHashMap<String , AlbumNewListByDateBean.MonthList> hashMap = new LinkedHashMap<String ,AlbumNewListByDateBean.MonthList>();
            for(int i = 0 ; i < newList.size() ; i++) {
                String key = newList.get(i);
                LogInfo.log("king","year key = " + key);
                JSONObject monthValue = getJSONObject(data, key);
                AlbumNewListByDateBean.MonthList monthList = null;
                if (monthValue!=null) {
                        monthList = new AlbumNewListByDateBean.MonthList();
                        Iterator<String> monthIter = monthValue.keys();
                        ArrayList<String> newListMonth = setNewDate(new ArrayList<String>() , monthIter);
                        for(int j = 0 ; j < newListMonth.size() ; j++){
                            String monthKey = newListMonth.get(j);
                            LogInfo.log("king","month key = " + monthKey);
                            org.json.JSONArray monthArray = getJSONArray(monthValue, monthKey);

                            ArrayList<VideoBean> list = new ArrayList<VideoBean>();
                            if (monthArray!=null && monthArray.length()>0) {
                                for (int z = 0; z < monthArray.length(); z++){
                                    JSONObject obj = monthArray.getJSONObject(z);
                                    list.add(JSON.parseObject(obj.toString(), VideoBean.class));
                                }
                            }
                            monthList.put(monthKey,list);
                            
                            /*
                             * Added by chenhong, for compatible with small window
                             */
                            VideoListBean videoListPlayerLibs = null;
            				if (videoListPlayerLibs == null) {
            					videoListPlayerLibs= new VideoListBean();
            				}
            				videoListPlayerLibs.addAll(list);
            				mTabAllDataBean.setVideoListPlayerLibs(videoListPlayerLibs);
            				
//                            TabVideoListBean tabVideoListBean = new TabVideoListBean();
//                            tabVideoListBean.setVideoInfoList(list);
//                            mTabAllDataBean.getTabVideoList().getTabIndicatorData().setVideoList(tabVideoListBean);
                        }
                }
                hashMap.put(key,(AlbumNewListByDateBean.MonthList)changeHashMap(monthList,null));
            }
            albumNewListByDatePlayerLibs.setYearList((LinkedHashMap<String , AlbumNewListByDateBean.MonthList>)changeHashMap(null,hashMap));
            return albumNewListByDatePlayerLibs;
	    }catch (Exception e ){
	        e.printStackTrace();
	    }
		return null;
	}
	
	/*
	 * Added by chenhong 2015-05-14
	 * 将年月时间数据放入列表
	 */
	private ArrayList<String> setNewDate(ArrayList<String> list, Iterator<String> iter) {
	   	 while (iter.hasNext()) {
	   		 String key = iter.next();
	   		 if (TextUtils.isDigitsOnly(key)) {
	   			 list.add(key);
	   		 }
	   	 }
	   	 Collections.sort(list, new MyComparator());
	   	 return list;
	}
	
	/*
	 * Added by chenhong 2015-05-14
	 * 对年月数据进行降序排列，最新的数据放在显示列表最上面
	 */
	public Object changeHashMap(AlbumNewListByDateBean.MonthList monthMap,LinkedHashMap<String , AlbumNewListByDateBean.MonthList> yearMap){
       int length = 0;
       if(monthMap!=null){
           length = monthMap.size();
       }
       if(yearMap!=null){
           length = yearMap.size();
       }
       String keys[] = new String[length];
       Object objs[] = new Object[length];
       AlbumNewListByDateBean.MonthList tempMonthMap = new AlbumNewListByDateBean.MonthList();
       LinkedHashMap<String,AlbumNewListByDateBean.MonthList> tempYearMap = new LinkedHashMap<String, AlbumNewListByDateBean.MonthList>();
       Iterator<String> mapKey = null;
       if(monthMap!=null){
           mapKey = monthMap.keySet().iterator();
       }
       if(yearMap!=null){
           mapKey = yearMap.keySet().iterator();
       }
       int i = 0;
       while (mapKey.hasNext()){
           String key  = mapKey.next();
           keys[i] = key;
           if(monthMap!=null){
               objs[i] = monthMap.get(key);
           }
           if(yearMap!=null){
               objs[i] = yearMap.get(key);
           }
           i++;
       }

       if(monthMap!=null){
           for(i=length-1;i>=0;i--){
               tempMonthMap.put(keys[i],(ArrayList<VideoBean>)objs[i]);
           }
           return tempMonthMap;
       }
       if(yearMap!=null){
           for(i = length-1; i >= 0; i--){
               tempYearMap.put(keys[i],(AlbumNewListByDateBean.MonthList)objs[i]);
           }
           return tempYearMap;
       }
       return null;
   }
   
	/*
	 * Added by chenhong 2015-05-14
	 * 升序排列
	 */
   class MyComparator implements Comparator<String>{
	    public int compare(String arg0, String arg1){
		    int s1 = Integer.parseInt(arg0);
		    int s2 = Integer.parseInt(arg1);
		    if(s1 > s2){
		    	return 1;
		    }else if(s1 == s2){
		    	return 0;
		    }else{
		    	return -1;
		    }
	    }
   }
	
	/*
	 * Relate List
	 */
	private void parseRelateList(String data) {
		mTabAllDataBean.getTabRelate().getTabIndicatorData().setVideoList(JSON.parseObject(data, TabVideoListBean.class));
	}
	
	@Override
    protected boolean canParse(String data) {
        return true;
    }

    @Override
    protected JSONObject getData(String data) throws JSONException {
        return new JSONObject(data);
    }
}
